package com.asj.vivo.lock.mq;

import android.os.AsyncTask;

import com.asj.config.RabbitMQHelper;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;

//MQ发送消息工具类
public class SendMessageTask extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... messages) {
        RabbitMQHelper helper = new RabbitMQHelper();
        ConnectionFactory factory = helper.getConnectionFactory();
        try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) {
            String exchangeName = "androidMdmExchange";
            String routingKey = "";
            String queueName = "aisheji.android.mdm.queue";

            // 声明交换和停止，并约束他们
            channel.exchangeDeclare(exchangeName, "fanout", true,false,null);  // durable exchange
            channel.queueDeclare(queueName, true, false, false, null);  // durable queue
            channel.queueBind(queueName, exchangeName, "");

            // 以持久模式发布消息
            String message = messages[0];
            channel.basicPublish(exchangeName, routingKey,
                    new com.rabbitmq.client.AMQP.BasicProperties.Builder()
                            .deliveryMode(2)  // make message persistent
                            .build(),
                    message.getBytes(StandardCharsets.UTF_8));
            System.out.println(" [x] Sent '" + message + "'");
            System.out.println("发送的消息是"+message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
